from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_squared_error
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import SGDRegressor
import joblib

import ssl
import certifi
ssl._create_default_https_context = lambda *args, **kwargs: ssl.create_default_context(cafile=certifi.where())

def linear_model1():

    #获取数据
    data = fetch_openml(name="boston", version=1, as_frame=True)
    #数据集划分
    x_train, x_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.2, random_state=22)
    #特征工程-标准化
    transfer = StandardScaler()
    x_train = transfer.fit_transform(x_train)
    x_test = transfer.transform(x_test)
    #机器学习-线性回归-正规方程
    estimator = LinearRegression()
    estimator.fit(x_train, y_train)
    #模型评估
    #获取系数等值
    y_predict = estimator.predict(x_test)
    print("预测值为:\n", y_predict)
    print("模型中的系数为:\n", estimator.coef_)
    print("模型中的偏置为:\n", estimator.intercept_)

    #计算误差
    error = mean_squared_error(y_test, y_predict)
    print("误差为:\n", error)
    return estimator

def linear_model2():
    #获取数据
    # 获取数据
    data = fetch_openml(name="boston", version=1, as_frame=True)
    # 数据集划分
    x_train, x_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.2, random_state=22)
    # 特征工程-标准化
    transfer = StandardScaler()
    x_train = transfer.fit_transform(x_train)
    x_test = transfer.transform(x_test)
    # 机器学习-线性回归-正规方程
    estimator = SGDRegressor(max_iter=1000)
    estimator.fit(x_train, y_train)
    # 模型评估
    # 获取系数等值
    y_predict = estimator.predict(x_test)
    print("预测值为:\n", y_predict)
    print("模型中的系数为:\n", estimator.coef_)
    print("模型中的偏置为:\n", estimator.intercept_)

    # 计算误差
    error = mean_squared_error(y_test, y_predict)
    print("误差为:\n", error)
    return estimator

if __name__ == '__main__':
    # estimator = linear_model2()
    # joblib.dump(estimator, 'model/test.pkl')
    estimator = joblib.load('../../../model/test.pkl')
    print(estimator.coef_)
    print(estimator.intercept_)